const express = require('express');
const index = require('../api/index');
const getResult = require("../utils/getResult");
const databasePublic = require("../utils/databasePublic");
const database = new databasePublic(); //获取数据库方法

var Router = express.Router();

Router.post('/trainStationList', async (req, result) => { //查询车站信息
  const findRes = await database.find({ //查询本地库是否存在
    library: "config",
    listName: "trainStationList",
    whereStr: "trainStationList"
  }).catch((err) => {
    console.log(err, "查询车站信息")
    result.json(getResult.busy());
  });
  if (findRes && findRes.length) { //存在返回
    result.json(getResult.success({
      Result: {
        trainStationList: findRes[0].trainStationList
      }
    }));
  } else {  //不存在或查询失败
    const trainStationListRes = await index.trainStationList().catch(err => { //请求第三方
      console.log(err, "查询车站信息")
      result.json(getResult.busy());
    });
    if (!trainStationListRes) return;
    if (trainStationListRes.data.Code == "0") { //获取到返回值后
      const insertOneRes = await database.insertOne({
        library: "config",
        listName: "trainStationList",
        message: {
          trainStationList: {
            hotStations: trainStationListRes.data.Result.hotStations,
            stations: trainStationListRes.data.Result.stations
          },
        }
      }).catch((err) => {
        console.log(err, "查询车站信息")
        result.json(getResult.busy());
      });
      if (!insertOneRes) return;
      result.json(getResult.success({
        Result: trainStationListRes.data.Result
      }));
    } else {
      result.json(getResult.fail({
        Result: trainStationListRes.data.Result
      }));
    };
  };
});
/**
 * get
 * // var require = JSON.stringify(req);
 * // var requireUrl = req.url;
 * 
 * post
 * 
 * //req.body
 * 
 */
module.exports = Router;